package com.iamteer.day11;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LastVisit
 */
@WebServlet("/LastVisit")
public class LastVisit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LastVisit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String lastVisit = "";
		boolean flag = false;
		
		
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				String name = c.getName();
				if("lastTime".equals(name)){
					lastVisit = c.getValue();
					flag = true;
					break;
				}
			}
		}
		response.setContentType("text/html;charset=utf-8");
		String content = "";
		if (flag) {
			content = "欢迎回来！你上次访问时间是：" + lastVisit + "！ ";
		}else {
			content = "这是您首次访问！ ";
		}
		content += "<br/>当前时间：";
		Date date = new Date();
		Cookie cookie = new Cookie("lastTime", date.toString());
		cookie.setMaxAge(30*24*60*60);
		response.addCookie(cookie);
		response.getWriter().write(content + date.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
